package org.lds.message.center.aliyun.autoconfigure;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.RequiredArgsConstructor;
import org.lds.message.center.aliyun.AliyunSmsHandler;
import org.lds.message.center.aliyun.AliyunSmsMessageService;
import org.lds.message.center.aliyun.constant.AliyunSmsConstant;
import org.lds.message.center.aliyun.consumer.AliyunSmsConsumer;
import org.lds.message.center.aliyun.enums.AliyunSmsErrorEnum;
import org.lds.message.center.aliyun.health.endpoint.AliyunSmsHealthEndpoint;
import org.lds.message.center.aliyun.properties.AliyunSmsProperties;
import org.lds.message.center.aliyun.starter.AliyunSmsRegisterAdmin;
import org.lds.message.center.common.exception.BusinessException;
import org.lds.message.center.plugin.core.kafka.KafkaProducer;
import org.lds.message.center.plugin.core.remote.RemoteService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = AliyunSmsConstant.ALIYUN_SMS_PREFIX, name = "enabled", havingValue = "true")
@EnableConfigurationProperties({AliyunSmsProperties.class})
public class AliyunSmsMessageAutoConfiguration {
    private final AliyunSmsProperties aliyunSmsProperties;

    @Bean
    public AliyunSmsMessageService aliyunSmsMessageService(KafkaProducer kafkaProducer, AliyunSmsHandler aliyunSmsHandler) {
        return new AliyunSmsMessageService(aliyunSmsHandler, aliyunSmsProperties, kafkaProducer);
    }

    @Bean
    public AliyunSmsHandler aliyunSmsHandler() {
        return new AliyunSmsHandler(aliyunSmsClient());
    }

    private Client aliyunSmsClient() {
        Config config = new Config()
                .setAccessKeyId(aliyunSmsProperties.getAccessKeyId())
                .setAccessKeySecret(aliyunSmsProperties.getAccessKeySecret());
        config.endpoint = aliyunSmsProperties.getEndpoint();

        try {
            return new Client(config);
        } catch (Exception e) {
            throw new BusinessException(AliyunSmsErrorEnum.CLIENT_CREATE_FAIL);
        }
    }

    @Bean
    public AliyunSmsConsumer aliyunSmsConsumer(AliyunSmsMessageService aliyunSmsMessageService) {
        return new AliyunSmsConsumer(aliyunSmsMessageService);
    }

    @Bean
    public AliyunSmsRegisterAdmin aliyunSmsRegisterAdmin(RemoteService remoteService) {
        return new AliyunSmsRegisterAdmin(remoteService);
    }

    @Bean
    public AliyunSmsHealthEndpoint aliyunSmsHealthEndpoint() {
        return new AliyunSmsHealthEndpoint();
    }

}
